import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { message, Form } from 'antd'
import moment from 'moment'
import { useRecoilValue } from 'recoil'
import { ReviewInfoHook, ReviewInfo } from '../data'

import { getInjuryInformation, getReviewInfo, updatePassAndNoPass } from '../service'
import { isNullArray, isNullData, isSuccess } from '@/utils'
import { TableList } from '@/pages/UpdateReview/data'
import { IPressure } from '@/@types/common'
import { userInfo } from '@/store/userInfo'
import { getWard } from '@/pages/ReportDetail/service'

export default (): ReviewInfoHook => {
  // 用户信息
  const userMsg = useRecoilValue(userInfo)
  const location = useLocation()
  const navigate = useNavigate()
  const [rejectForm] = Form.useForm()
  const [formObj] = Form.useForm()
  const { id, dataId, createTime, status, hospitalId } = location.state as TableList

  // 事件数据
  const [eventList, setEventList] = useState<IPressure[]>([])
  // 书数据
  const [reviewInfo, setReviewInfo] = useState<ReviewInfo | undefined>()
  // 开关状态
  const [switchChecked, setSwitchChecked] = useState<boolean>(true)
  // modal
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
  // 控制modal
  const [visible, setVisible] = useState<boolean>(false)
  // 病区级联
  const [wardList, setWardList] = useState<any[]>([])

  // 递归函数，将原始数据转换为 Cascader 数据结构
  const transformDataCatalogue = (items: any) =>
    items.map((item: any) => {
      const dis = item.type === '20' && item.endemicAreaVos.length === 0
      const cascaderItem: any = {
        label: item.unit,
        value: item.id.toString(),
        disabled: dis,
      }
      if (item.endemicAreaVos.length > 0) {
        cascaderItem.children = transformDataCatalogue(item.endemicAreaVos)
      }
      return cascaderItem
    })

  // 获取病区级联
  const getWardHandle = async () => {
    if (!userMsg.hospitalCode) return
    const params = {
      hospitalCode: userMsg.hospitalCode,
    }
    const res = await getWard(params)
    if (isNullData(res) && res.data) {
      console.log(
        'transformDataCatalogue(res.data.endemicAreaVos)🚀🚀🚀🚀',
        transformDataCatalogue(res.data.endemicAreaVos),
      )
      setWardList(transformDataCatalogue(res.data.endemicAreaVos))
    }
  }

  // 获取信息
  const getInfo = async () => {
    const res = await getReviewInfo({
      dataId,
      updateId: id,
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setReviewInfo(res.data)
    } else {
      setReviewInfo(undefined)
    }
  }

  const getInjuryInfo = async () => {
    const res = await getInjuryInformation({
      dataId,
      updateId: id,
    })
    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setEventList(res.data)
    } else {
      setEventList([])
    }
    console.log('事件内容🚀🚀🚀🚀', res)
  }
  // 开关
  const handleSwitchChange = (checked: boolean) => {
    setSwitchChecked(checked)
  }

  // 同意
  const handleAgree = async () => {
    const newlist = reviewInfo!.sortPlatformVos
      .map((item) => item.variablePlatformVos.filter((val) => val.updateVariableId))
      .flat()
      .map((newval) => newval.updateVariableId)
    console.log('newlist🚀🚀🚀🚀', newlist)
    const juryIds = eventList.map((item) => item.id)
    const res = await updatePassAndNoPass({
      applyStatus: '1',
      ids: newlist,
      dataId,
      updateId: id,
      injuryIds: juryIds,
    })
    if (isNullData(res) && res.data && isNullArray(res.data) && isSuccess(res.data)) {
      message.success('操作成功')
      navigate(-1)
    } else {
      message.error(res.data?.message)
    }
    console.log('res🚀🚀🚀🚀', res)
  }

  // 不同意点击
  const handleAgreeCancel = () => {
    setIsModalOpen(true)
  }

  // 关闭modal
  const handleCancelModal = () => {
    setIsModalOpen(false)
    rejectForm.resetFields()
  }

  // 原因提交
  const onFinish = async (values: { backReason: string }) => {
    console.log(values)
    const res = await updatePassAndNoPass({
      applyStatus: '2',
      dataId,
      updateId: id,
      backReason: values.backReason,
    })
    if (isNullData(res) && res.data && isNullArray(res.data) && isSuccess(res.data)) {
      message.success('操作成功')
      handleCancelModal()
      navigate(-1)
    } else {
      message.error(res.data?.message)
    }
  }

  // modal确定
  const handleOk = (isHCancel: boolean) => {
    console.log('确定🚀🚀🚀🚀')
  }
  // 取消关闭回调
  const handleCancel = () => {
    console.log('取消🚀🚀🚀🚀')
    formObj.resetFields()
    setVisible(false)
  }

  // 查看
  const handlePreview = (list: IPressure) => {
    formObj.setFieldsValue({
      ...list,
      admissionTime: moment(list.admissionTime),
      happenDate: moment(list.happenDate),
      happenArea: list.happenAreaId.split('/'),
    })
    setVisible(true)
  }

  useEffect(() => {
    getInfo()
    getInjuryInfo()
    getWardHandle()
  }, [])

  return {
    reviewInfo,
    switchChecked,
    handleSwitchChange,
    createTime,
    status,
    handleAgree,
    isModalOpen,
    handleCancelModal,
    rejectForm,
    handleAgreeCancel,
    onFinish,
    handlePreview,
    eventList,
    wardList,
    IndicatorsModal: {
      formObj,
      visible,
      handleOk,
      handleCancel,
      wardList,
      hospitalId,
    },
  }
}
